package com.youyi.yychosesdk.utils.permission;

import android.app.Activity;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import java.util.ArrayList;
import java.util.List;

public class PermissionUtil {

    public interface PermissionCallBack {
        void onFailed();

        void onShouldShow();

        void onSuccess();
    }

    public static boolean checkAndRequestPermissionsInActivity(Activity activity, String... strArr) {
        ArrayList arrayList = new ArrayList();
        boolean z = true;
        for (String str : strArr) {
            if (PermissionChecker.checkSelfPermission(activity, str) != 0) {
                arrayList.add(str);
                z = false;
            }
        }
        if (!z) {
            requestPermissionsInActivity(activity, 12, (String[]) arrayList.toArray(new String[arrayList.size()]));
        }
        return z;
    }

    private static void requestPermissionsInActivity(Activity activity, int i, String... strArr) {
        ActivityCompat.requestPermissions(activity, strArr, i);
    }

    public static void onPermissionResult(Activity activity, String[] strArr, int[] iArr, PermissionCallBack permissionCallBack) {
        int length = iArr.length;
        ArrayList arrayList = new ArrayList();
        if (length > 0) {
            for (int i = 0; i < length; i++) {
                if (iArr[i] != 0) {
                    arrayList.add(Integer.valueOf(i));
                }
            }
        }
        if (arrayList.size() == 0) {
            permissionCallBack.onSuccess();
        } else {
            progressNoPermission(activity, permissionCallBack, strArr, arrayList, 0);
        }
    }

    private static void progressNoPermission(Activity activity, PermissionCallBack permissionCallBack, String[] strArr, List<Integer> list, int i) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, strArr[list.get(i).intValue()])) {
            permissionCallBack.onShouldShow();
        } else if (i < list.size() - 1) {
            progressNoPermission(activity, permissionCallBack, strArr, list, i + 1);
        } else {
            permissionCallBack.onFailed();
        }
    }
}
